package DBD::Yahoo::db;    # ====== DATABASE ======

use strict;
use base qw(DBD::_::db);
use vars qw($VERSION $imp_data_size);

use DBI;

use SQL::Parser;

$VERSION       = "0.01";
$imp_data_size = 0;

sub prepare
{
  my ($dbh, $statement, @attr) = @_;

  my $parser = SQL::Parser->new;
  $parser->parse($statement) or die $parser->errstr;
  my $structure = $parser->structure;

  # Get the yahoo instance and %attr
  my $yahoo = $dbh->FETCH('driver_yahoo') || die $!;
  my $search_opts = $dbh->FETCH('driver_yahoo_opts');

  my $arg1 = $structure->{'where_clause'}->{'arg1'}->{'value'} || 'Doc';
  $arg1 = ucfirst lc $arg1;
  my $arg2 = $structure->{'where_clause'}->{'arg2'}->{'value'} || '?';
  $arg2 =~ tr/'"//;

  my $sth = DBI::_new_sth(
    $dbh,
    {
      'YahooSearch' => $yahoo,
      'Statement'   => $statement,
      'Columns'     => $structure->{'column_names'},
      'Space'       => $arg1,
      'Query'       => $arg2,
      'Start'       => $structure->{'limit_clause'}->{'offset'} || $yahoo->{'Start'} || 0,
      'Count'       => $structure->{'limit_clause'}->{'limit'} || $yahoo->{'Count'} || 10,
    }
  );

  $sth->STORE('driver_params', []);

  return $sth;
}

sub STORE
{
  my ($dbh, $attr, $val) = @_;
  if ($attr eq 'AutoCommit')
  {
    return 1;
  }

  if ($attr =~ m/^driver_/)
  {
    $dbh->{$attr} = $val;
    return 1;
  }

  $dbh->SUPER::STORE($attr, $val);
}

sub FETCH
{
  my ($dbh, $attr) = @_;

  if ($attr eq 'AutoCommit')
  {
    return 1;
  }
  elsif ($attr =~ m/^driver_/)
  {
    return $dbh->{$attr};
  }

  $dbh->SUPER::FETCH($attr);
}

sub commit
{
  my $dbh = shift;

  warn "Commit ineffective while AutoCommit is on"
    if $dbh->FETCH('Warn');

  1;
}

sub rollback
{
  my $dbh = shift;

  warn "Rollback ineffective while AutoCommit is on"
    if $dbh->FETCH('Warn');

  0;
}

sub get_info
{
  my ($dbh, $info_type) = @_;
  require DBD::Yahoo::GetInfo;
  my $v = $DBD::Yahoo::GetInfo::info{ int($info_type) };
  $v = $v->($dbh) if ref $v eq 'CODE';
  return $v;
}

1;
